import { deepClone, getTypeof, isEmpty } from 'src/utils/utils'

export function labelKey (props = {}) {
  if (props.label) return props.label.split(',').map(el => el.trim())
  return ['label']
}

export function valueKey (props = {}) {
  return props.value || 'value'
}

const fillStr = '--'

export function getLabel (scope, props) {
  if (isEmpty(scope)) return ''

  if (getTypeof(scope) !== 'object') return scope

  const keyList = labelKey(props)

  let str = ''
  for (const key of keyList) {
    str += `${fillStr}${scope[key]}`
  }
  return str.replace(fillStr, '')
}

export function getValue (scope, props) {
  if (isEmpty(scope)) return ''

  if (getTypeof(scope) !== 'object') return scope

  return scope[valueKey(props)]
}

export function getDisable (scope, props) {
  if (isEmpty(scope)) return false
  const type = getTypeof(scope)
  if (!['object', 'array'].includes(type)) return false
  const key = props ? props.disable || 'isEnable' : 'disable'
  if (type === 'object') return [true, '0'].includes(scope[key])

  return !!scope.filter(el => [true, '0'].includes(el[key])).length
}

export function formatLabels (scope = {}, props, formatLabel) {
  if (isEmpty(scope)) return ''

  const formatFunc = formatLabel || getLabel

  if (getTypeof(scope) === 'array') return scope.map(el => formatFunc(el, props)).join(',')

  return formatFunc(scope, props)
}

export function formatValues (scope = {}, props) {
  if (isEmpty(scope)) return ''

  if (getTypeof(scope) === 'array') return scope.map(el => getValue(el, props)).join(',')

  return getValue(scope, props)
}

export function filterList (list = [], props, query) {
  if (isEmpty(query)) return list

  query = query.toLowerCase()

  return list.filter(el => String(getLabel(el, props)).toLowerCase().includes(query))
}

export function selectUnique (list, props, isDeep) {
  const res = new Map()
  if (isDeep) list = deepClone(list)
  return list.filter(el => !res.has(getValue(el, props)) && res.set(getValue(el, props), 1))
}